package com.neu.cloudFactory.service;

import com.neu.cloudFactory.DAO.FactoryDAO;
import com.neu.cloudFactory.DAO.UserDAO;
import com.neu.cloudFactory.PO.Factory;
import com.neu.cloudFactory.VO.FactoryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class FactoryService {
    final FactoryDAO factoryDAO;
    final UserDAO userDAO;

    public FactoryService(FactoryDAO factoryDAO, UserDAO userDAO) {
        this.factoryDAO = factoryDAO;
        this.userDAO = userDAO;
    }

    //列出所有工厂
    public List<FactoryVO> findAllFactoryVO() {
        List<Factory> factories = factoryDAO.findAll();
        List<FactoryVO> factoryVOList = new ArrayList<>();
        for (Factory factory : factories) {
            factoryVOList.add(
                    new FactoryVO(factory, userDAO.getById(factory.getUserId())));
        }
        return factoryVOList;
    }

    //修改工厂
    public void modifyFactory(Factory factory) {
        factoryDAO.save(factory);
    }

    //开启工厂
    public void openFactory(Factory factory) {
        factoryDAO.modifyState("正常", factory.getId());
    }

    //关闭工厂
    public void closeFactory(Factory factory) {
        factoryDAO.modifyState("关停", factory.getId());
    }

    public Factory findFactoryById(int id) {
        return factoryDAO.getById(id);
    }

    //找到userID对应的factory
    public Factory findFactoryByUserId(int id) {
        return factoryDAO.findByUserId(id);
    }

    //新增工厂
    public void addFactory(Factory factory){
        factoryDAO.save(factory);
    }

    //根据userid删除对应工厂
    public void deleteByUserId(int userId){
        Factory factory = factoryDAO.findByUserId(userId);
        factoryDAO.delete(factory);
    }

    public Factory changeType(FactoryVO factoryVO) {
        Factory factory = new Factory();
        factory.setId(Integer.parseInt(factoryVO.getId()));
        factory.setName(factoryVO.getName());
        factory.setDetail(factoryVO.getDetail());
        factory.setState(factoryVO.getState());
        factory.setUserId(userDAO.findByName(factoryVO.getManager()).getId());
        return factory;
    }
}
